package com.gitee.ywj1352.gateway.Iloadbalance;

import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.Server;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.List;
import java.util.stream.Collectors;

public class ZookeeperLoadBalancer extends BaseLoadBalancer {

    @Value("${spring.application.name}")
    private String currentService;

    private final DiscoveryClient discoveryClient;
    public ZookeeperLoadBalancer(DiscoveryClient discoveryClient){
        this.discoveryClient = discoveryClient;
        updateServers();
    }

    @Scheduled(fixedDelay = 10000)
    public void updateServers(){
        discoveryClient.getServices().forEach(serviceName -> {
            if (!serviceName.equals(currentService)){
                List<ServiceInstance> instances = discoveryClient.getInstances(serviceName);
                List<Server> serverList = instances.stream().map(s -> {
                    return new Server(s.isSecure()?"https://":"http://", s.getHost(), s.getPort());
                }).collect(Collectors.toList());
                addServers(serverList);
            }
        });
    }

}
